<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :span="6">
            <a-form-model-item label="商户/菜品名称">
              <a-input v-model="queryParam.tradeName" />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="上架状态">
              <a-select v-model="queryParam.upFlag" :allowClear="true" @change="searchQuery">
                <a-select-option value="YES">上架中</a-select-option>
                <a-select-option value="NO">下架中</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="handleAdd" type="primary" icon="plus">新增</a-button>
      <a-button @click="saveBatchEdit">保存</a-button>

      <!--      <a-button type="primary" icon="download" @click="handleExportXls('商品')">导出</a-button>-->
      <!--      <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl" @change="handleImportExcel">-->
      <!--        <a-button type="primary" icon="import">导入</a-button>-->
      <!--      </a-upload>-->
      <!-- 高级查询区域 -->
      <!--      <j-super-query :fieldList="superFieldList" ref="superQueryModal" @handleSuperQuery="handleSuperQuery"></j-super-query>-->
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel"> 删除 </a-menu-item>
          <a-menu-item key="2" @click="$refs.batchModifyInventory.show(selectionRows)"> 修改库存 </a-menu-item>
          <a-menu-item key="3" @click="showChangeOrderstate('上架中')"> 上架 </a-menu-item>
          <a-menu-item key="4" @click="showChangeOrderstate('下架中')"> 下架 </a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px">
          批量操作
          <a-icon type="down" />
        </a-button>
      </a-dropdown>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择
        <a style="font-weight: 600">{{ selectedRowKeys.length }}</a
        >项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        :scroll="{ x: true }"
        :bordered="false"
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        :loading="loading"
        class="j-table-force-nowrap"
        @change="handleTableChange"
      >
        <template slot="stateSlot" slot-scope="text, record, index">
          <a-switch
            :loading="record.stateLoading"
            checked-children="上架中"
            un-checked-children="下架中"
            :checked="record.upFlag == '上架中' ? true : false"
            @click="stateEdit(record, index)"
          />
        </template>
        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="imgSlot" slot-scope="text, record, index">
          <span v-if="!text" style="font-size: 12px; font-style: italic">无图片</span>
          <img
            v-else
            :src="getImgView(text)"
            height="25px"
            alt=""
            style="max-width: 80px; font-size: 12px; font-style: italic"
            @click="showCropper(index)"
          />
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px; font-style: italic">无文件</span>
          <a-button v-else :ghost="true" type="primary" icon="download" size="small" @click="downloadFile(text)">
            下载
          </a-button>
        </template>
        <template slot="tradeNameSlot" slot-scope="text, record, index">
          <div v-if="!record.isEdit">{{ record.tradeName }}</div>
          <a-input v-else v-model="record.tradeName" />
        </template>
        <template slot="productDescriptionSlot" slot-scope="text, record, index">
          <div v-if="!record.isEdit">{{ record.productDescription }}</div>
          <a-input v-else v-model="record.productDescription" />
        </template>
        <template slot="limitBuySlot" slot-scope="text, record, index">
          <div v-if="!record.isEdit">{{ record.limitBuy }}</div>
          <a-input-number v-else v-model="record.limitBuy" />
        </template>
        <template slot="sortSlot" slot-scope="text, record, index">
          <div v-if="!record.isEdit">{{ record.sort }}</div>
          <a-input-number v-else v-model="record.sort" />
        </template>

        <span slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)">编辑</a>
          <a-divider type="vertical" />
          <a @click="handleEdit(record, 'copy')">复制</a>
          <a-divider type="vertical" />
          <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
            <a>删除</a>
          </a-popconfirm>
          <!--          <a-dropdown>-->
          <!--            <a class="ant-dropdown-link">更多 <a-icon type="down" /></a>-->
          <!--            <a-menu slot="overlay">-->
          <!--              <a-menu-item>-->
          <!--                <a @click="handleDetail(record)">详情</a>-->
          <!--              </a-menu-item>-->
          <!--              <a-menu-item>-->
          <!--                <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">-->
          <!--                  <a>删除</a>-->
          <!--                </a-popconfirm>-->
          <!--              </a-menu-item>-->
          <!--            </a-menu>-->
          <!--          </a-dropdown>-->
        </span>
      </a-table>
    </div>

    <hc-commodity-modal ref="modalForm" @ok="modalFormOk"></hc-commodity-modal>
    <BatchModifyInventory ref="batchModifyInventory" @ok="modalFormOk"></BatchModifyInventory>
    <ImgCropper ref="imgCropper" @getImgSrc="getImgSrc"></ImgCropper>
    <a-modal v-model="visiable" title="提示" @ok="handleOk">
      <p>您即将保存您当前的所有修改，此行为不可撤销，是否继续</p>
    </a-modal>
  </a-card>
</template>

<script>
import '@/assets/less/TableExpand.less'
import { mixinDevice } from '@/utils/mixin'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import HcCommodityModal from './modules/HcCommodityModal'
import BatchModifyInventory from './modules/batchModifyInventory.vue'
import { deleteAction, postAction, getAction } from '@api/manage'
import ImgCropper from './modules/imgCropper.vue'

export default {
  name: 'HcCommodityList',
  mixins: [JeecgListMixin, mixinDevice],
  components: {
    HcCommodityModal,
    BatchModifyInventory,
    ImgCropper,
  },
  data() {
    return {
      description: '商品管理页面',
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: '商户',
          align: 'center',
          dataIndex: 'merchantId_dictText',
        },
        {
          title: '商品名称',
          align: 'center',
          dataIndex: 'tradeName',
          scopedSlots: { customRender: 'tradeNameSlot' },
        },
        {
          title: '商品描述',
          align: 'center',
          dataIndex: 'productDescription',
          scopedSlots: { customRender: 'productDescriptionSlot' },
        },
        {
          title: '商品价格',
          align: 'center',
          dataIndex: 'commodityPrice',
        },
        {
          title: '商品图片',
          align: 'center',
          dataIndex: 'productPicture',
          scopedSlots: { customRender: 'imgSlot' },
        },
        // {
        //   title:'规格',
        //   align:"center",
        //   dataIndex: 'commoditySpecifications'
        // },
        {
          title: '限购',
          align: 'center',
          dataIndex: 'limitBuy',
          scopedSlots: { customRender: 'limitBuySlot' },
        },
        {
          title: '排序',
          align: 'center',
          dataIndex: 'sort',
          scopedSlots: { customRender: 'sortSlot' },
        },
        {
          title: '上架状态',
          align: 'center',
          dataIndex: 'upFlag',
          scopedSlots: { customRender: 'stateSlot' },
        },
        {
          title: '已售数量',
          align: 'center',
          dataIndex: 'soldCount',
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 147,
          scopedSlots: { customRender: 'action' },
        },
      ],
      url: {
        list: '/hc/hcCommodity/list',
        delete: '/hc/hcCommodity/delete',
        deleteBatch: '/hc/hcCommodity/deleteBatch',
        exportXlsUrl: '/hc/hcCommodity/exportXls',
        importExcelUrl: 'hc/hcCommodity/importExcel',
      },
      dictOptions: {},
      superFieldList: [],

      cropperImgIndex: '',
      visiable: false,
    }
  },
  created() {
    this.getSuperFieldList()
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
  },
  methods: {
    //初始化数据
    loadData(arg) {
      console.log('555')
      if (!this.url.list) {
        this.$message.error('请设置url.list属性!')
        return
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
      }
      var params = this.getQueryParams() //查询条件
      this.loading = true
      getAction(this.url.list, params)
        .then((res) => {
          if (res.success) {
            this.dataSource = res.result.records || res.result
            this.dataSource.forEach((item) => {
              item.isEdit = true
            })
            if (res.result.total) {
              this.ipagination.total = res.result.total
            } else {
              this.ipagination.total = 0
            }
            //update-end---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    //展示批量编辑
    showBatchEdit() {
      this.dataSource.forEach((item) => {
        item.isEdit = true
      })
      this.$forceUpdate()
    },
    //显示批量保存的弹窗
    saveBatchEdit() {
      let flag = false;
      for (let i = 0; i < this.dataSource.length; i++) {
        let item = this.dataSource[i]
        let { merchantId_dictText, tradeName,limitBuy } = item;
        console.log('limitBuy',limitBuy)
        if (!limitBuy) {
          this.$message.warning(`${merchantId_dictText}的${tradeName}商品库存不能为空`)
          flag = true
          break
        }
        if (limitBuy < -1) {
          this.$message.warning(`${merchantId_dictText}的${tradeName}商品库存不能小于-1`)
          flag = true
          break
        }
        if (String(limitBuy).split('.').length != 1) {
          this.$message.warning(`${merchantId_dictText}的${tradeName}商品库存只能为整数`)
          flag = true
          break
        }
      }
      if (flag) {
        return
      }
      this.visiable = true
    },
    //确认批量保存
    async handleOk() {
      let res = await postAction('/hc/hcCommodity/editBatch', this.dataSource)
      console.log('res', res)
      if (res.success) {
        this.$message.success('数据保存成功')
        this.loadData()
        this.visiable = false
      } else {
        this.$message.warning(res.message)
      }
    },

    showCropper(index) {
      console.log('index', index)
      this.$refs.imgCropper.show()
      this.cropperImgIndex = index
    },
    //图片裁剪上传后的回调
    getImgSrc(value) {
      this.dataSource[this.cropperImgIndex].productPicture = value
      this.$forceUpdate()
    },

    handleEdit(record, type) {
      console.log('type', type)
      if (type != 'copy') {
        this.$refs.modalForm.title = '编辑'
      } else {
        this.$refs.modalForm.title = '复制'
        record.id = ''
      }
      this.$refs.modalForm.edit(record, type)
      this.$refs.modalForm.disableSubmit = false
    },
    stateEdit(record, index) {
      let that = this
      this.$set(this.dataSource[index], 'stateLoading', true)
      let state = record.upFlag == '上架中' ? '下架中' : '上架中'
      postAction('/hc/hcCommodity/editUpFlag', { id: record.id, upFlag: state })
        .then((res) => {
          if (res.success) {
            that.loadData()
          } else {
            that.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.$set(this.dataSource[index], 'stateLoading', false)
        })
    },
    initDictConfig() {},
    getSuperFieldList() {
      let fieldList = []
      fieldList.push({ type: 'string', value: 'merchantId', text: '商户ID' })
      fieldList.push({ type: 'string', value: 'tradeName', text: '商品名称' })
      fieldList.push({ type: 'number', value: 'commodityPrice', text: '商品价格' })
      fieldList.push({ type: 'string', value: 'productPicture', text: '商品图片' })
      fieldList.push({ type: 'string', value: 'commoditySpecifications', text: '规格' })
      fieldList.push({ type: 'int', value: 'limitBuy', text: '限购' })
      fieldList.push({ type: 'int', value: 'upFlag', text: '是否上架' })
      this.superFieldList = fieldList
    },
    showChangeOrderstate(type) {
      let that = this

      this.$confirm({
        title: '',
        content: '是否确定把选中数据的上架状态改为' + type + '?',
        onOk: function () {
          that.loading = true
          postAction('/hc/hcCommodity/editUpFlagBatch', { selections: that.selectedRowKeys.join(','), upFlag: type })
            .then((res) => {
              if (res.success) {
                that.loadData()
                that.onClearSelected()
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.loading = false
            })
        },
      })
    },
  },
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>